package org.example.likou150.tree;

// https://leetcode.cn/problems/path-sum/?envType=study-plan-v2&envId=top-interview-150
public class Flatten {
    public static void main(String[] args) {

    }

    // 正确做法，后序遍历

    TreeNode preNode = null;
    public void flatten(TreeNode root) {
        if(root!=null){
            flatten(root.right);
            flatten(root.left);

            root.left = null;
            root.right = preNode;
            preNode = root;
        }
    }



    // 错误做法，因为树结构被打乱了
//    private TreeNode preNode = null;
//    public void flatten(TreeNode root) {
//        if(root == null){
//            return;
//        }
//        if(preNode == null){
//            preNode = root;
//        }
//        preNode.left = null;
//        preNode.right = root;
//        preNode = root;
//        flatten(root.left);
//        flatten(root.right);
//    }

    public class TreeNode {
     int val;
     TreeNode left;
     TreeNode right;
     TreeNode() {}
     TreeNode(int val) { this.val = val; }
     TreeNode(int val, TreeNode left, TreeNode right) {
         this.val = val;
         this.left = left;
         this.right = right;
     }
    }
}
